【发布时间】:2016-09-24 20:17:55
【问题描述】:
我试图在 Activity 中为片段充气,这是代码。
public class DetailActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container2, new DetailFragment())
.commit(); //Line with Error
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.detail, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_refresh) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
这是我的DetailFragment 课程
/**
* A placeholder fragment containing a simple view.
*/
public class DetailFragment extends Fragment {
public DetailFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
return rootView;
}
}
这是fragment_detail的布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:textSize="18sp"
android:id="@+id/fragment_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
我面临的错误是cannot resolve method 'add(int,com.example...DetailFragment)'。由于我是android初学者,还请指导我应该如何处理此类错误。
【问题讨论】:
-
您为
DetailFragment导入了错误的Fragment类。应该是android.support.v4.app Fragment。 -
很抱歉,我没有收到你。
-
查看
import类中的import语句。说import android.app.Fragment;的那个应该是import android.support.v4.app.Fragment;。
标签: android android-fragments error-handling exception-handling