很明显,我对Android - XML编程很陌生.因此,我有一个导航抽屉,一旦从抽屉中选择项目,右侧就会显示相应的片段。在那个片段里,我有线性布局。一旦线性布局被打开,我想重定向到另一个活动。通过使用android:onClick on XML文件,我能够让它在活动中工作,但不能让它在片段上工作。谁来帮帮我。
App接口,请参阅此图像:
http://i.stack.imgur.com/u6dHi.jpg
代码:
fragment_smart.xml -一旦项目被选中就显示。我试图在xml上使用onClick。
<LinearLayout
android:id="@+id/linearLayoutsmart1"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_below="@+id/smart_title"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
android:orientation="horizontal"
android:weightSum="1"
android:onClick="smart_recommended_link">这里是我的代码
public class FragmentSmart extends Fragment {
public static final String TAG = "stats";
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myfragment = inflater.inflate(R.layout.fragment_smart, container, false);
return myfragment;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public void smart_recommended_link(View view) {
Intent smartRecommendedIntent = new Intent(this, SmartRecommended.class);
startActivity(smartRecommendedIntent);
}}
当我使用这段代码点击线性布局时,这个应用程序就崩溃了。这里最好的办法是什么?谢谢!
发布于 2015-09-14 14:32:52
对于片段,需要以编程方式添加侦听器:
public class MyFragment extends Fragment implements View.OnClickListener {
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.my_layout).setOnClickListener(this);
}
@Override
public void onClick(View v) {
// Handle click based on v.getId()
}
}发布于 2015-09-14 14:36:21
首先,在默认情况下,线性布局不能触发onClick事件。请查看此答案以获得更多信息:LinearLayout onClick。
您可以从您的LinearLayout视图中获得如下所示的onCreateView():
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myfragment = inflater.inflate(R.layout.fragment_smart, container, false);
LinearLayout layout = (LinearLayout)myFragment.findViewById(R.id.linearLayoutsmart1);
// here you can set a listener of any type you want to the layout
return myfragment;
}发布于 2015-09-14 14:50:41
在片段中,必须使用getActivity()方法而不是this来引用片段所附加的活动。
public void smart_recommended_link(View view) {
Intent smartRecommendedIntent = new Intent(getActivity(), SmartRecommended.class);
startActivity(smartRecommendedIntent);
}https://stackoverflow.com/questions/32567349
复制相似问题