在框架内创建一个ontouchlistener视图

时间:2017-03-07 17:00:44

标签: android android-fragments ontouchlistener

如何为只包含片段的帧创建onTouchListener?我不需要膨胀一个activity_main文件,因为它会在调用此片段时显示。如果我试图给框架本身充气,它会抛出“预期的类型布局资源”错误。

当用户触摸按钮时片段将被激活,片段应在帧中打开。框架还需要能够听取触摸事件。

这就是我现在片段的片段和onCreateView:

public class TeacherFragment extends Fragment {

public final String TAG = getClass().getSimpleName();

public void onAttach(Activity myActivity){

    Log.v(TAG, "in TeacherFragment - onAttach, activity is: " + myActivity);
    super.onAttach(myActivity);
}

/**
 * This method will only be called once when the retained
 * Fragment is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Retain this fragment across configuration changes.
    setRetainInstance(true);
}

/**
 * This method will be called only when
 * Fragment is attached and ready to display the view.
 */
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle SavedInstanceState){

    if(container == null) {
        Log.v(TAG, "container is null. No need to inflate.");
        return null;
    }

    View v = container.findViewById(R.id.assignment_view);
    v.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            Log.d(TAG, "onShortPress: " + event.toString());
            Toast.makeText(getView().getContext(), "Testing Short click", Toast.LENGTH_SHORT).show();
            return true;
        }

        public void onLongPress(MotionEvent event) {
            Log.d(TAG, "onLongPress: " + event.toString());
            Toast.makeText(getView().getContext(), "Testing Long click", Toast.LENGTH_SHORT).show();
        }
    });

    return v;
}  //end onCreateView

}

这是我的activity_main。我正在尝试仅为此片段使用assignment_view框架。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/main_layout"
android:baselineAligned="false">

<FrameLayout
    android:id="@+id/main_menu_frame"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:background="#FF0000"
    android:layout_weight=".3">
</FrameLayout>

<FrameLayout
    android:layout_width="8dp"
    android:layout_height="match_parent"
    android:background="#000000">
</FrameLayout>

<FrameLayout
    android:id="@+id/assignment_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00BBFF"
    android:layout_weight="8">
</FrameLayout>

</LinearLayout>

1 个答案:

答案 0 :(得分:0)

您应该只对文件使用inflate()。你的&#34;布局中的一个&#34;夹。这是错误消息告诉您的内容。不花很多时间看这个,你可能想要这个

View v = findViewById(R.id.assignment_view);

为你的&#34; activity_main.xml&#34;文件,它可能更好地在这里充气,而不是依赖于调用活动中膨胀的东西。