public class MainActivity extends AppCompatActivity{

  int value=0;
  TextView mText;

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

    mText=(TextView)findViewById(R.id.text);
    mHandler.sendEmptyMessage(0);
  }

  class MyHandler extends Handler{
    public void handleMessage(Message msg){
      value++;
      mText.setText("Value="+value);
      mHandler.sendEmptyMessageDelayed(0,1000);
    }
  }
  Handler mHandler = new MyHandler();

  public void mOnClick(View v){
    TextView textFruit = (TextView)findViewById(R.id.fruit);
    switch (v.getId()){
      case R.id.apple:
        textFruit.setText("Apple");
        break;
     case R.id.orange:
       textFruit.setText("Orange");
       break;
    }
  }
}

 

=====================================

public class MainActivity extends AppCompatActivity{

  int value=0;
  TextView mText;
  Handler mHandler;

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

    mText=(TextView)findViewById(R.id.text);

    mHandler = new Handler(){
      public void handleMessage(Message msg){
        value++;
        mText.setText("Value="+value);
        mHandler.sendEmptyMessageDelayed(0,1000);
      }
    };
    mHandler.sendEmptyMessageDelayed(0,1000);
  }

  public void mOnClick(View v){
    TextView textFruit = (TextView)findViewById(R.id.fruit);
    switch (v.getId()){
      case R.id.apple:
        textFruit.setText("Apple");
        break;
      case R.id.orange:
        textFruit.setText("Orange");
        break;
    }
  }
}

==================================================

activity_main.xml

==================================================

<?xml version="1.0" encoding="utf-8"?>
  <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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
      android:layout_width="wrap_content"
      android:id="@+id/fruit"
      android:layout_height="wrap_content"
      android:text="fruit"
      android:textColor="#ffff00"
      android:textSize="48sp" />
    <LinearLayout
      android:layout_width="wrap_content"
      android:layout_height="match_parent"
    >
    <Button
      android:id="@+id/apple"
      android:layout_height="wrap_content"
      android:layout_width="wrap_content"
      android:text="apple"
    />
    <Button
      android:id="@+id/orange"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="orange"
    />
  </LinearLayout>

</LinearLayout>

-----------------------------------------------------------

 

 

===========================================

MainActivity.java

===========================================

public class MainActivity extends AppCompatActivity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btnApple=(Button)findViewById(R.id.apple);
    btnApple.setOnClickListener(new Button.OnClickListener(){
      public void onClick(View v){
        TextView textfruit = (TextView)findViewById(R.id.fruit);
        textfruit.setText("Apple");
    }
  });

  Button btnOrange=(Button)findViewById(R.id.orange);
    btnOrange.setOnClickListener(new Button.OnClickListener(){
      public void onClick(View v){
        TextView textfruit = (TextView)findViewById(R.id.fruit);
        textfruit.setText("Orange");
     }
    });
  }
}

 

 

==============================================================

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

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

    Button btnApple=(Button)findViewById(R.id.apple);
    btnApple.setOnClickListener(this);

    Button btnOrange=(Button)findViewById(R.id.orange);
    btnOrange.setOnClickListener(this);
  }

  public void onClick(View v){
    TextView textFruit = (TextView)findViewById(R.id.fruit);
    switch (v.getId()){
      case R.id.apple:
        textFruit.setText("Apple");
        break;
      case R.id.orange:
        textFruit.setText("Orange");
        break;
    }
  }
}

 

=======================================

 

public class MainActivity extends AppCompatActivity{

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

    findViewById(R.id.apple).setOnClickListener(mClickListener);
    findViewById(R.id.orange).setOnClickListener(mClickListener);
  }

  Button.OnClickListener mClickListener = new View.OnClickListener(){
    public void onClick(View v){
      TextView textFruit = (TextView)findViewById(R.id.fruit);
      switch (v.getId()){
        case R.id.apple:
          textFruit.setText("Apple");
          break;
        case R.id.orange:
          textFruit.setText("Orange");
          break;
      }
    }
  };
}

 

==========================================================================

<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".MainActivity">

  <TextView
    android:layout_width="wrap_content"
    android:id="@+id/fruit"
    android:layout_height="wrap_content"
    android:text="fruit"
    android:textColor="#ffff00"
    android:textSize="48sp" />
      <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
     >
       <Button
         android:id="@+id/apple"
         android:layout_height="wrap_content"
         android:layout_width="wrap_content"
         android:text="apple"
         android:onClick="mOnClick"
       />
      <Button
        android:id="@+id/orange"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="orange"
        android:onClick="mOnClick"
      />
     </LinearLayout>
</LinearLayout>

 

=====================================================================

public class MainActivity extends AppCompatActivity{

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

  public void mOnClick(View v){
    TextView textFruit = (TextView)findViewById(R.id.fruit);
    switch (v.getId()){
      case R.id.apple:
        textFruit.setText("Apple");
        break;
     case R.id.orange:
       textFruit.setText("Orange");
       break;
    }
  }
}


public class MainActivity extends AppCompatActivity {
   private MyView vw;
   public class Vertex{
      Vertex(float ax, float ay, boolean ad){
         x = ax;
         y = ay;
         draw = ad;
      }
      float x;
      float y;
      boolean draw;
   }

   ArrayList<Vertex> arVertex;

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      vw = new MyView(this);
      setContentView(vw);

      arVertex = new ArrayList<Vertex>();
   }

   protected class MyView extends View{
      Paint mPaint;
      public MyView(Context context){
         super(context);
         mPaint = new Paint();
         mPaint.setColor(Color.BLACK);
         mPaint.setStrokeWidth(3);
         mPaint.setAntiAlias(true);
      }

      public void onDraw(Canvas canvas){
         canvas.drawColor(Color.LTGRAY);

         for (int i=1;i<arVertex.size();i++){
            if (arVertex.get(i).draw){
               canvas.drawLine(arVertex.get(i-1).x,arVertex.get(i-1).y,arVertex.get(i).x,arVertex.get(i).y,mPaint);
            }
         }
      }
      public boolean onTouchEvent(MotionEvent event){
         if (event.getAction()==MotionEvent.ACTION_DOWN){
            arVertex.add(new Vertex(event.getX(),event.getY(),true));
            return true;
         }
         if(event.getAction()==MotionEvent.ACTION_MOVE){
            arVertex.add(new Vertex(event.getX(),event.getY(),true));
            invalidate();
            return true;
         }
         return false;
      }
   }
}

 

같은 결과를 도출하지만 약간씩 다른 방법으로 리스너를 구현했습니다.

 

콜백메서드 재정의

 

public class MainActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    View vw = new MyView(this);
    setContentView(vw);
  }

  class MyView extends View{
    public MyView(Context context){
    super(context);
  }

  public boolean onTouchEvent(MotionEvent event){
    super.onTouchEvent(event);
    if (event.getAction() == MotionEvent.ACTION_DOWN){
      Toast.makeText(this.getContext(), "touch Event Received",Toast.LENGTH_SHORT).show();
      return true;
    }
    return false;
  }

}

 

리스너 인터페이스 구현

public class MainActivity extends AppCompatActivity {
  TextView mResult;
  final int READ_CONTACT_CODE = 0;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    View vw = new View (this);
    vw.setOnTouchListener(TouchListener);
    setContentView(vw);
  }

  class TouchListenerClass implements View.OnTouchListener {
    public boolean onTouch(View v,MotionEvent event){
      if (event.getAction() == MotionEvent.ACTION_DOWN){
        Toast.makeText(MainActivity.this,"touch Event Received",Toast.LENGTH_SHORT).show();
        return true;
      }
      return false;
    }
  }
  return false;
  TouchListenerClass TouchListener = new TouchListenerClass();

}

 

=========================================================

액티비티 리스너 구현

 

public class MainActivity extends AppCompatActivity implements View.OnTouchListener{
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    View vw = new View (this);
    vw.setOnTouchListener(this);
    setContentView(vw);
  }

  public boolean onTouch(View v,MotionEvent event){
    if (event.getAction() == MotionEvent.ACTION_DOWN){
      Toast.makeText(MainActivity.this,"touch Event Received",Toast.LENGTH_SHORT).show();
      return true;
    }
    return false;
  }
}

 

===================================

View에서 리스너 구현

 

public class MainActivity extends AppCompatActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    MyView vw = new MyView (this);
    vw.setOnTouchListener(vw);
    setContentView(vw);
  }

  class MyView extends View implements View.OnTouchListener{
    public MyView(Context context){
      super(context);
    }
    public boolean onTouch(View v,MotionEvent event){
      if (event.getAction() == MotionEvent.ACTION_DOWN){
        Toast.makeText(MainActivity.this,"touch Event Received",Toast.LENGTH_SHORT).show();
        return true;
      }
      return false;
    }
  }
}

 

=====================================

익명 내부 클래스 이용 리스너 구현

 

public class MainActivity extends AppCompatActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    View vw = new View (this);
    vw.setOnTouchListener(TouchListener);
    setContentView(vw);
  }

  View.OnTouchListener TouchListener = new View.OnTouchListener(){
    public boolean onTouch(View v,MotionEvent event){
      if (event.getAction() == MotionEvent.ACTION_DOWN){
        Toast.makeText(MainActivity.this,"touch Event Received",Toast.LENGTH_SHORT).show();
        return true;
      }
      return false;
    }
  };
}

 

 

===================================================================

<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/linear"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<Button
android:id="@+id/btnread"
android:layout_width="269dp"
android:layout_height="58dp"
android:layout_marginBottom="208dp"
android:text="주소록 읽기"/>

<Button
android:id="@+id/btnreset"
android:layout_width="267dp"
android:layout_height="55dp"
android:layout_marginBottom="136dp"
android:text="리셋" />

<TextView
android:id="@+id/result"
android:layout_width="244dp"
android:layout_height="61dp"
android:layout_marginBottom="188dp"
android:text="TextView" />

</LinearLayout>

 

---------------------------------------------------------------------

 

public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      LinearLayout MyLinear = (LinearLayout) findViewById(R.id.linear);
      MyLinear.setOnTouchListener(TouchListener);
   }

   View.OnTouchListener TouchListener = new View.OnTouchListener(){
      public boolean onTouch(View v,MotionEvent event){
         if (event.getAction() == MotionEvent.ACTION_DOWN){
            TextView text = (TextView)findViewById(R.id.result);
            text.setText("touched");
            return true;
         }
         return false;
      }
   };
}

onRequestPermissionsResult needs AppCompatActivity inheritance

 

and READ_CONTACT_CODE needs definition so if you don't want new definition then you can put 1 instead of that.

 

==========================================

public class MainActivity extends AppCompatActivity {
TextView mResult;
final int READ_CONTACT_CODE = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mResult=(TextView)findViewById(R.id.result);
}

public void mOnClick(View v)
{
switch (v.getId()){
case R.id.btnread:
tryOutContact();
break;
case R.id.btnreset:
mResult.setText("내 주소록");
break;
}
}
void tryOutContact(){
if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)== PackageManager.PERMISSION_GRANTED){
outContact();
}
else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, READ_CONTACT_CODE);
}
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);

switch (requestCode) {
case 1:
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission is granted. Continue the action or workflow
// in your app.
outContact();
} else {
// Explain to the user that the feature is unavailable because
// the features requires a permission that the user has denied.
// At the same time, respect the user's decision. Don't link to
// system settings in an effort to convince the user to change
// their decision.
}
return;
}
// Other 'case' lines to check for other
// permissions this app might request.
}

void outContact(){
ContentResolver cr=getContentResolver();
Cursor cusor = cr.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);
int nameidx = cusor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);

if (cusor.moveToNext()){
mResult.setText(cusor.getString(nameidx));
}else {
mResult.setText("주소록이 비어있습니다.");
}
cusor.close();
}
}

 

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">


<Button
android:id="@+id/btnread"
android:layout_width="269dp"
android:layout_height="58dp"
android:layout_marginTop="76dp"
android:text="주소록 읽기"
android:onClick="mOnClick"
app:layout_constraintBottom_toTopOf="@+id/btnreset"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/btnreset"
android:layout_width="267dp"
android:layout_height="55dp"
android:layout_marginBottom="76dp"
android:text="리셋"
android:onClick="mOnClick"
app:layout_constraintBottom_toTopOf="@+id/result"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />

<TextView
android:id="@+id/result"
android:layout_width="244dp"
android:layout_height="61dp"
android:layout_marginBottom="128dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

안드로이드에서는  보안과 관련된 중요한 사항에 사용자의 허가를 받아야 하는데, 허가가 필요한 사항응 반드시 manifest에 명시해야하는데 빨간색과 같이 표시하면 된다.

 

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
       
package="com.example.snazzyapp">

   
<uses-permission android:name="android.permission.INTERNET"/>
   
<!-- other permissions go here -->

   
<application ...>
        ...
   
</application>
</manifest>

 

한편 사용자의 허가를 받아야하는 서비스는 아래 표와 같으며 이들 서비스를 사용할 때는 위의 manifest에 반드시 명시해야하며 한번 허가받으면 다시 받을 필요가 없으나 사용자는 언제든 허가를 취소할 수 있다. 그리고, 권한이 없을 때는 사용자에게 권한을 요청해야만 한다.

 

서 비 스   이 름 설          명
LAYOUT_INFLATER_SERVICE 전개자
AUDIO_SERVICE 오디오 관리자
DOWNLOAD_SERVICE 다운로드 관리자
VIBRATOR_SERVICE 진동관리자
LOCATION_SERVICE 위치 서비스 관리자
POWER_SERVICE 전원 관리자

 

 

 

 

+ Recent posts