在android中接受长按/点击线性布局?

use*_*544 5 long-click android-widget android-layout android-linearlayout onlongclicklistener

我是android的新手,我遇到了一堵墙.

我正在尝试使用线性布局来更像按钮,使用不同的按下和长按操作 - 原因是因此我可以在每个"按钮"上有2个不同格式的文本标签.有点像:

-------------------------
|          2nd          |  <- Label for long press (regular/smaller type)
|           =           |  <- Label for regular press (bold/larger type)
-------------------------
Run Code Online (Sandbox Code Playgroud)

我发现的帖子解释了如何定期点击线性布局(我使用布局XML中的onClick属性).但是长按我没有运气.我试图为xml定义一个新的onLongClick属性,如Aleksander Gralak在这里的答案所述:XML布局中的长按定义,如android:onClick.但没有这样的运气 - 它看起来像是用于文本视图,我尝试将其更改为线性布局,但失败了.

这是有问题的对象: Main.xml

<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:clickable="true"
    android:focusable="true"
    android:background="@drawable/darkgrey_button"
    android:onClick="equals" android:longClickable="true" android:id="equalsbutton"
    android:focusableInTouchMode="false">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="2nd"
        android:id="@+id/textView"
        android:duplicateParentState="true"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=" = "
        android:id="@+id/textView1"
        android:duplicateParentState="true"/>
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

Main.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

public void equals(View view) {
    Context context = getApplicationContext();
    CharSequence text = "Hello toast!";
    int duration = Toast.LENGTH_SHORT;

    Toast toast = Toast.makeText(context, text, duration);
    toast.show();
}
Run Code Online (Sandbox Code Playgroud)

Rag*_*har 6

添加id到您的布局.

<LinearLayout
    android:id="@+id/my_button_layout"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    … >
Run Code Online (Sandbox Code Playgroud)

在你的 Main.java

获取您的参考LinearLayout并设置一个OnLongClickListener.

LinearLayout buttonLayout = (LinearLayout) findViewById(R.id.my_button_layout);
…
buttonLayout.setOnLongClickListener(new OnLongClickListener() {

    @Override
    public boolean onLongClick(View v) {
          Toast.makeText(Main.this, "Long click!", Toast.LENGTH_SHORT).show();
          return true;
    }

});
Run Code Online (Sandbox Code Playgroud)