【问题标题】:Receive a long press/click on a linear layout in android?收到长按/点击android中的线性布局?
【发布时间】:2013-03-13 04:12:54
【问题描述】:

我对 android 很陌生,而且我碰壁了。

我正在尝试让线性布局更像一个按钮,按下和长按的动作不同 - 原因是我可以在每个“按钮”上有 2 个不同格式的文本标签。大致如下:

-------------------------
|          2nd          |  <- Label for long press (regular/smaller type)
|           =           |  <- Label for regular press (bold/larger type)
-------------------------

我发现的帖子解释了如何在线性布局上接收常规点击(我在布局 XML 中使用 onClick 属性)。但是长按我没有运气。我试图为 xml 定义一个新的 onLongClick 属性,如 Aleksander Gralak 的回答中所述:Long press definition at XML layout, like android:onClick does。但是没有这样的运气 - 它看起来像是用于文本视图,我尝试将其更改为线性布局但失败了。

这里是有问题的对象: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>

还有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();
}

【问题讨论】:

    标签: android-layout android-widget android-linearlayout onlongclicklistener long-click


    【解决方案1】:

    在您的布局中添加id。

    <LinearLayout
        android:id="@+id/my_button_layout"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        … >
    

    在你的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;
        }
    
    });
    

    【讨论】:

    • 这里的总体思路对我有用。我能够在 WebView 对象上设置监听器
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多