2015-03-13 2 views
0

Я создал три кнопки, и каждая кнопка показывает текст при нажатии. Теперь мне нужно добавить к этому, чтобы кнопки отображали текст + изображение. все тексты и изображения будут отображаться только при нажатии кнопок. Например, когда пользователь нажимает на первую кнопку, появляется текст1 + изображение1. Когда пользователь нажимает на вторую кнопку, text2 + image2 появляется в тех же местах text1 и image1. Любая помощь, пожалуйста? вот мои коды:Как создавать кнопки, отображающие изображения?

XML (я не мог опубликовать первую часть кода здесь, но ниже наиболее важные части)

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Recipe 1" 
    android:id="@+id/click_btn" 
    android:layout_alignParentTop="true" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentStart="true" /> 
<TextView 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/response" 
    android:layout_below="@+id/click_btn" 
    android:layout_alignParentBottom="true" 
    android:layout_alignRight="@+id/button15" 
    android:layout_alignEnd="@+id/button15" /> 

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Recipe 2" 
    android:id="@+id/button15" 
    android:layout_alignParentTop="true" 
    android:layout_centerHorizontal="true" /> 

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Recipe 3" 
    android:id="@+id/button16" 
    android:layout_alignParentTop="true" 
    android:layout_alignParentRight="true" 
    android:layout_alignParentEnd="true" /> 

<ImageView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/imageView4" 
    android:layout_centerVertical="true" 
    android:layout_toRightOf="@+id/response" 
    android:layout_toEndOf="@+id/response" /> 

</RelativeLayout> 

Java:

package com.example.android.ch; 

import android.content.pm.ActivityInfo; 
import android.content.res.Configuration; 
import android.support.v7.app.ActionBarActivity; 
import android.os.Bundle; 
import android.view.Display; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.WindowManager; 
import android.widget.Button; 
import android.widget.ImageView; 
import android.widget.TextView; 
import android.widget.Toast; 

import static com.example.android.R.*; 


public class Recipes extends ActionBarActivity implements View.OnClickListener { 
TextView resp; ImageView imageView; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(layout.activity_recipes); 
    resp = (TextView)this.findViewById(id.response); 
    Button b = (Button)this.findViewById(id.click_btn); 
    Button c = (Button)this.findViewById(id.button15); 
    Button d = (Button)this.findViewById(id.button16); 
    ImageView imageView = (ImageView) findViewById(id.imageView); 
    b.setOnClickListener(this); 
    c.setOnClickListener(this); 
    d.setOnClickListener(this); 

} 

@Override 
public void onConfigurationChanged(Configuration newConfig) { 
    super.onConfigurationChanged(newConfig); 


    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { 



    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){ 

    } 
} 



@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_recipes, menu); 
    return true; 

} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    if (id == R.id.action_settings) { 
     return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 

@Override 
public void onClick(View v) { 

    switch(v.getId()){ 

     case R.id.click_btn: /** on click_btn button click */ 
      resp.setText("2 medium sweet potatoes (about 1 pound total) \n1/2 teaspoon salt\n1/2 teaspoon ground cumin\n1/2 teaspoon chili powder\n1/2 teaspoon paprika\n1/4 teaspoon ground black pepper"); 
      break; 

     case R.id.button15: /** on button15 button click */ 
      resp.setText("1 large egg yolk, at room temperature\n1/2 cup extra-virgin olive oil; more for grilling\n2 teaspoons minced fresh flat-leaf parsley\n1 teaspoon minced fresh tarragon\n1 1/2 teaspoons fresh lemon juice; more to taste Kosher salt"); 
      break; 

     case R.id.button16: /** on button16 button click */ 
      resp.setText("1/2 cup butter, softened\n1 cup packed light brown sugar\n1 1/2 cups all-purpose flour\n3 cups rolled oats\n1 teaspoon ground cinnamon"); 
      break; 
    } 
} 

} 
+0

Вместо этого вы можете использовать ImageButtons. Чтобы вы могли отображать изображение или текст на кнопке. –

ответ

0

Я получил правильный ответ со многими из вас и поблагодарил всех вас, но я хотел создать три кнопки и показать текст + изображение Не внутри значка. Для этого я создал три фрагмента xml-файлов, поэтому, когда пользователь нажимает кнопку, он выведет фрагмент и разместит его.

1

да, вы можете добавить изображение или значок на кнопку с текстом. использование ниже кода для этого -

<Button 
    android:drawableRight="@drawable/ic_logout" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Recipe 3" 
    android:id="@+id/button16" 
    android:layout_alignParentTop="true" 
    android:layout_alignParentRight="true" 
    android:layout_alignParentEnd="true" /> 

здесь я добавил еще одно свойство андроида: drawableRight вы можете изменить его на андроида: drawableLeft, андроида: drawableTop или андроида: drawableBottom и установить изображение на кнопку.

+0

Я пытаюсь добавить текст + изображение не внутри значка. –

+0

Можете ли вы привести пример изображения, какой дизайн вам нужен, тогда он станет более полезным – Ravi

1

Использование drawableLeft (или любое направление) атрибута, чтобы отобразить изображение с текстом,

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/button_text" 
    android:drawableLeft="@drawable/button_icon" 
    ... /> 

Приведенный выше код будет отображать изображение как enter image description here

0

включают ImageView и TextView в макете и сохранить его видимость как невидимые /gone.Then при нажатии кнопки (например, button1) внутри метода прослушивания onclick вам нужно попробовать, например,

измените этот код внутри каждого прослушивателя buttonclick с различным значением.

Смежные вопросы