Tuesday, July 26, 2016

TextSwitcher Android


activity_layout
<LinearLayout  
xmlns:android="http://schemas.android.com/apk/res/android" 
 xmlns:app="http://schemas.android.com/apk/res-auto" 
 xmlns:tools="http://schemas.android.com/tools" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" 
 android:orientation="vertical">

    <TextView 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 android:layout_gravity="center" 
 android:text="TextSwitcher" />

    <TextSwitcher 
 android:id="@+id/textSwitcher" 
 android:layout_width="match_parent" 
 android:layout_height="wrap_content" 
 android:layout_gravity="center_horizontal" 
 android:layout_margin="50dp" />

    <Button 
 android:id="@+id/btnClick" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 android:layout_gravity="center" 
 android:layout_margin="20dp" 
 android:text="Click" />
</LinearLayout>
 
MainActivity
 
public class MainActivity extends AppCompatActivity implements ViewSwitcher.ViewFactory {
    String TAG = "MainActivity";
    TextSwitcher textSwitcher;
    Button btnClick;
    int a = 0;

    @Override 
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        textSwitcher = (TextSwitcher) findViewById(R.id.textSwitcher);
        textSwitcher.setFactory(MainActivity.this);
        Animation in = AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
        Animation out = AnimationUtils.loadAnimation(this, android.R.anim.fade_out);

        textSwitcher.setInAnimation(in);
        textSwitcher.setOutAnimation(out);
        btnClick = (Button) findViewById(R.id.btnClick);
        btnClick.setOnClickListener(new View.OnClickListener() {
            @Override 
 public void onClick(View view) {
                a++;
                textSwitcher.setText("" + a);
            }
        });

    }


    @Override 
 public View makeView() {
        TextView t = new TextView(this);
        t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
        t.setTextSize(50);
        return t;
    }
}
 

No comments:

Post a Comment