开发者

Android Eclipse development Clickable..text pops up

开发者 https://www.devze.com 2023-03-28 09:17 出处:网络
I have the following code: <TextView android:text=\"Color Yellow\" android:textColor=\"#000000\" android:gravity=\"center_horizontal\"

I have the following code:

<TextView
    android:text="Color Yellow"
    android:textColor="#000000"
    android:gravity="center_horizontal"
    android:background="#aaaa00"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:clickable="True"
/>

The android:clickable="True" was added because I thought it needed to be there (please do correct me if I'm wrong). However, the answer I'开发者_如何学编程m seeking right now is how do I go by making another box (filled with text) pop-up upon clicking the "yellow box".

I would be grateful if someone could provide me with ideas and/or hints regarding how to actually create this scenario.


The android:clickable element does what you think and what it name tells you. It allows you to receive click events for that view (TextView here) to act on these.

To create a popup, you have to assign something to that TextView that tells you when it actually gets clicked. That is a OnClickListener. You can do that either in code or partially in code and XML. I'll just focus on the code example, but for the record, the XML one is also pretty easy. It involves setting the android:onClick="myOnClick" attribute to a certain function name that you like ("myOnClick" here) and creating a function like public void myOnClick(View v) in your activity.

What you have to do in code is

  1. Referencing the TextView that you have in your layout
  2. Assign the OnClickListener
  3. Write an action that will be executed once the click gets registered

First point: To reference your TextView you have to use findViewById

TextView myTextView = (TextView) findViewById(R.id.mytextviewid);

Note that you have to assign a ID to your TextView to identify it. You can set that id via the android:id attribute in your XML layout (e.g. android:id="@+id/mytextviewid").

Second point: Once you have the reference, use TextView.setOnClickListener() to register one. This usually looks like this:

myTextView.setOnClickListener(new OnClickListener() {

      public void onClick(View v) {
            // Add an action here
      }
});

Third point: All you have to do now is displaying your dialog/message insite the onClick() function. There is more than one way to display that, you may use a Toast or an AlertDialog. Check out the links, there are some examples for that.

0

精彩评论

暂无评论...
验证码 换一张
取 消