【发布时间】:2015-06-21 15:15:40
【问题描述】:
我正在创建一个片段,其中我使用可点击的线性布局作为按钮 我已经创建了所有必要的方法并实现了类的 OnClickListener 接口但是当我单击布局时没有任何反应 这是我的 xml 和 java 代码中的 LinearLayout 和 TextView。
<LinearLayout
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_width="50dip"
android:layout_weight="1"
android:clickable="true"
android:background="@drawable/button_layout"
android:layout_margin="1dip">
<LinearLayout
android:orientation="vertical"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="e"
android:textColor="@color/abc_primary_text_disable_only_material_dark"
android:gravity="top"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="π"
android:gravity="bottom"/>
</LinearLayout>
</LinearLayout>
主视图TextView是
<TextView android:id="@+id/mainview"
android:layout_width="match_parent"
android:background="@color/button_material_light"
android:layout_height="60dip"
android:layout_weight="1"/>
类代码是
public class HomeFragment extends Fragment implements View.OnClickListener{
TextView mainView;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mainView = (TextView) getActivity().findViewById(R.id.mainview);
}
public static HomeFragment newInstance(int i){
HomeFragment homeFragment = new HomeFragment();
Bundle args = new Bundle();
args.putInt("index", i);
homeFragment.setArguments(args);
return homeFragment;
}
public HomeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(getArguments().getInt("index"));
}
@Override
public void onClick(View view) {
mainView.setText("ghalib");
}
}
我也试过调试程序,发现点击布局时没有调用该方法。
【问题讨论】:
-
你确定吗,你已经添加了mainView.setOnClickListener(this);
-
谢谢....rahul 我找到了解决方案,我忘记设置我的 LinearLayout 的列表器,顺便说一下 mainView 是我的 TextView,在我的布局中不可点击
-
嘿@rahul 是否可以在 xml 中为 onclicklistner 使用“this”对象
-
由于你的Activity实现了接口,你可以传递类上下文(this),它将委托给你类中编写的覆盖方法(onClick)。
标签: java android android-fragments android-linearlayout onclicklistener